<template>
	<view class="container">
		<view class="header">
			<text class="title">💡 健康建议</text>
			<text class="subtitle">基于您的健康状况，为您提供个性化建议</text>
		</view>

		<!-- 个性化建议 -->
		<view class="personalized-section">
			<view class="section-header">
				<text class="section-title">💡 个性化建议</text>
				<view class="header-actions">
					<button class="refresh-btn" @click="refreshAdvice" :disabled="isLoadingAdvice">
						{{isLoadingAdvice ? '生成中...' : '重新生成'}}
					</button>
				</view>
			</view>

			<!-- 加载状态 -->
			<view class="loading-advice" v-if="isLoadingAdvice">
				<view class="loading-icon">🤖</view>
				<text class="loading-text">AI正在生成个性化建议...</text>
			</view>

			<!-- AI建议列表 -->
			<view class="advice-cards" v-if="personalizedAdvice.length > 0">
				<view v-if="!healthData" class="history-tip">📚 显示历史建议记录</view>
				<view class="advice-card" v-for="(advice, index) in personalizedAdvice" :key="index"
					@click="openAdviceDetail(advice)">
					<view class="card-header">
						<view class="card-icon">{{advice.icon}}</view>
						<text class="card-title">{{advice.title}}</text>
						<view class="favorite-btn" @click.stop="toggleFavorite(advice)">
							<text :class="isFavorite(advice) ? 'star active' : 'star'">★</text>
						</view>
					</view>
					<text class="card-content">{{advice.content}}</text>
					<view class="card-tags">
						<text class="tag" v-for="(tag, tagIndex) in advice.tags" :key="tagIndex">{{tag}}</text>
					</view>
				</view>
			</view>

			<!-- 连接状态提示 -->
			<view class="connection-status" v-if="connectionError">
				<text class="status-text">⚠️ {{connectionError}}</text>
				<text class="status-hint">使用本地建议作为备选</text>
			</view>
		</view>

		<!-- 健康知识库 -->
		<view class="knowledge-section">
			<text class="section-title">📚 健康知识库</text>
			<view class="knowledge-list">
				<view class="knowledge-item" v-for="(item, index) in knowledgeItems" :key="index"
					@click="showKnowledgeDetail(item)">
					<view class="item-icon">{{item.icon}}</view>
					<view class="item-content">
						<text class="item-title">{{item.title}}</text>
						<text class="item-desc">{{item.description}}</text>
					</view>
					<view class="item-arrow">></view>
				</view>
			</view>
		</view>

		<!-- 系统健康提醒 -->
		<view class="reminder-section">
			<text class="section-title">⏰ 系统健康提醒</text>
			<view class="reminder-list">
				<view class="reminder-item" v-for="(reminder, index) in healthRemindersDefault" :key="'d'+index">
					<view class="reminder-time">{{reminder.time}}</view>
					<view class="reminder-content">
						<text class="reminder-title">{{reminder.title}}</text>
						<text class="reminder-desc">{{reminder.description}}</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 我的健康提醒 -->
		<view class="reminder-section">
			<text class="section-title">⏰ 我的健康提醒</text>
			<view class="reminder-list">
				<view class="reminder-item" v-for="(reminder, index) in healthRemindersCustom" :key="'c'+index">
					<view class="reminder-time">{{reminder.time}}</view>
					<view class="reminder-content">
						<text class="reminder-title">{{reminder.title}}</text>
						<text class="reminder-desc">{{reminder.description}}</text>
					</view>
					<view class="reminder-delete" @click.stop="deleteCustomReminder(index)">删除</view>
				</view>
				<view v-if="healthRemindersCustom.length === 0" style="text-align:center;color:#aaa;padding:20rpx;">
					暂无自定义提醒</view>
			</view>
		</view>

		<!-- 快速操作 -->
		<view class="quick-actions">
			<text class="section-title">⚡ 快速操作</text>
			<view class="action-grid">
				<view class="action-item" @click="openReminderModal">
					<view class="action-icon">⏰</view>
					<text class="action-text">设置提醒</text>
				</view>
				<view class="action-item" @click="shareHealth">
					<view class="action-icon">📤</view>
					<text class="action-text">分享健康</text>
				</view>
				<view class="action-item" @click="openReportModal">
					<view class="action-icon">📄</view>
					<text class="action-text">导出报告</text>
				</view>
				<view class="action-item" @click="contactDoctor">
					<view class="action-icon">👨‍⚕️</view>
					<text class="action-text">咨询医生</text>
				</view>
			</view>
		</view>

		<!-- 知识详情弹窗 -->
		<view class="modal-overlay" v-if="showModal" @click="closeModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">{{selectedKnowledge.title}}</text>
					<view class="modal-close" @click="closeModal">×</view>
				</view>
				<scroll-view class="modal-body" scroll-y>
					<text class="modal-text">{{selectedKnowledge.content}}</text>
				</scroll-view>
			</view>
		</view>

		<!-- 新增：自定义提醒弹窗 -->
		<view class="modal-overlay" v-if="showReminderModal" @click="closeReminderModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">添加健康提醒</text>
					<view class="modal-close" @click="closeReminderModal">×</view>
				</view>
				<view class="modal-body">
					<view class="form-item">
						<text class="label">提醒时间</text>
						<picker mode="time" :value="newReminder.time" @change="onReminderDateTimeChange">
							<view class="input" style="line-height: 40px;">
								{{ newReminder.time ? newReminder.time : '请选择日期和时间' }}
							</view>
						</picker>
						<text v-if="reminderErrors.time" class="error-text">{{reminderErrors.time}}</text>
					</view>
					<view class="form-item">
						<text class="label">提醒内容</text>
						<input class="input" type="text" v-model="newReminder.title" placeholder="请输入提醒内容"
							@blur="validateReminderTitle" />
						<text v-if="reminderErrors.title" class="error-text">{{reminderErrors.title}}</text>
					</view>
					<view class="form-item">
						<text class="label">详细描述</text>
						<input class="input" type="text" v-model="newReminder.description" placeholder="可选"
							@blur="validateReminderDesc" />
						<text v-if="reminderErrors.description" class="error-text">{{reminderErrors.description}}</text>
					</view>
					<button class="save-btn" @click="addCustomReminder">保存提醒</button>
				</view>
			</view>
		</view>

		<!-- 新增：健康报告导出弹窗 -->
		<view class="modal-overlay" v-if="showReportModal" @click="closeReportModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">健康报告</text>
					<view class="modal-close" @click="closeReportModal">×</view>
				</view>
				<view class="modal-body">
					<scroll-view style="max-height: 50vh;" scroll-y>
						<view class="modal-text" v-html="reportContentHtml"></view>
					</scroll-view>
					<button class="save-btn" @click="copyReport">复制报告</button>
				</view>
			</view>
		</view>

		<!-- 我的收藏区域 -->
		<view class="favorite-section" v-if="adviceFavorites.length > 0">
			<view style="display:flex;align-items:center;justify-content:space-between;">
				<text class="section-title">⭐ 我的收藏</text>
				<button class="save-btn" style="width:auto;padding:0 20rpx;font-size:24rpx;"
					@click="openExportFavoritesModal">导出/分享</button>
			</view>
			<view class="advice-cards">
				<view class="advice-card" v-for="(advice, index) in adviceFavorites" :key="'fav'+index">
					<view class="card-header">
						<view class="card-icon">{{advice.icon}}</view>
						<text class="card-title">{{advice.title}}</text>
						<view class="favorite-btn" @click.stop="toggleFavorite(advice)">
							<text class="star active">★</text>
						</view>
					</view>
					<text class="card-content">{{advice.content}}</text>
					<view class="card-tags">
						<text class="tag" v-for="(tag, tagIndex) in advice.tags" :key="tagIndex">{{tag}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 个性化建议详情弹窗 -->
		<view class="modal-overlay" v-if="showAdviceDetailModal" @click="closeAdviceDetailModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">{{adviceDetail.title}}</text>
					<view class="modal-close" @click="closeAdviceDetailModal">×</view>
				</view>
				<view class="modal-body">
					<view class="card-icon" style="font-size:48rpx;margin-bottom:10rpx;">{{adviceDetail.icon}}</view>
					<view class="card-content" style="margin-bottom:15rpx;">{{adviceDetail.description}}</view>
					<view class="card-tags" v-if="adviceDetail.tags && adviceDetail.tags.length">
						<text class="tag" v-for="(tag, tagIndex) in adviceDetail.tags" :key="tagIndex">{{tag}}</text>
					</view>
					<view style="margin-top:20rpx;text-align:right;">
						<button class="save-btn" style="width:auto;padding:0 30rpx;"
							@click.stop="toggleFavorite(adviceDetail)">
							<text :class="isFavorite(adviceDetail) ? 'star active' : 'star'">★</text>
							{{isFavorite(adviceDetail) ? '取消收藏' : '收藏'}}
						</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 收藏建议导出弹窗 -->
		<view class="modal-overlay" v-if="showExportFavoritesModal" @click="closeExportFavoritesModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">导出我的收藏</text>
					<view class="modal-close" @click="closeExportFavoritesModal">×</view>
				</view>
				<view class="modal-body">
					<scroll-view style="max-height: 50vh;">
						<view class="modal-text" style="white-space:pre-line;">{{exportFavoritesContent}}</view>
					</scroll-view>
					<button class="save-btn" @click="copyExportFavorites">复制内容</button>
					<!-- H5/APP原生分享按钮 -->
					<button class="save-btn" v-if="canNativeShare" @click="shareFavorites"
						style="margin-top:10rpx;">原生分享</button>
					<!-- 微信小程序原生分享按钮 -->
					<button class="save-btn" open-type="share" v-if="isMpWeixin"
						style="margin-top:10rpx;">微信小程序分享</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		healthAPI,
		parseAIResponse,
		favoritesAPI,
		remindersAPI,
		analysisAPI
	} from '../../utils/api.js'

	export default {
		data() {
			return {
				healthData: null,
				personalizedAdvice: [],
				isLoadingAdvice: false,
				connectionError: '',
				knowledgeItems: [{
						icon: '🥗',
						title: '健康饮食指南',
						description: '了解如何通过饮食改善健康状况',
						content: '健康饮食是维持身体健康的基础。建议每天摄入充足的蔬菜水果，适量蛋白质，控制脂肪和糖分摄入。多吃全谷物，少吃精制食品。注意饮食的多样性和均衡性。'
					},
					{
						icon: '🏃‍♂️',
						title: '运动健身指导',
						description: '科学运动，提升身体素质',
						content: '规律运动对健康至关重要。建议每周进行150分钟中等强度有氧运动，或75分钟高强度运动。同时进行力量训练，增强肌肉力量。运动前要热身，运动后要放松。'
					},
					{
						icon: '😴',
						title: '睡眠健康知识',
						description: '改善睡眠质量，提升生活品质',
						content: '充足的睡眠是身体恢复和大脑整理信息的重要时间。成年人建议每天睡7-9小时。保持规律的作息时间，创造良好的睡眠环境，避免睡前使用电子设备。'
					},
					{
						icon: '💧',
						title: '水分补充要点',
						description: '正确补充水分，维持身体机能',
						content: '人体约60%是水分，每天需要补充足够的水分。建议每天喝8杯水（约2升），运动时适当增加。注意观察尿液颜色，淡黄色表示水分充足。'
					},
					{
						icon: '🧘‍♀️',
						title: '心理健康维护',
						description: '关注心理健康，保持积极心态',
						content: '心理健康与身体健康同样重要。学会管理压力，保持积极心态。可以通过冥想、深呼吸、运动等方式缓解压力。必要时寻求专业心理咨询。'
					}
				],
				healthRemindersDefault: [{
						time: '08:00',
						title: '晨起喝水',
						description: '起床后喝一杯温水，促进新陈代谢'
					},
					{
						time: '12:00',
						title: '午餐时间',
						description: '注意营养均衡，细嚼慢咽'
					},
					{
						time: '15:00',
						title: '下午运动',
						description: '适当活动，缓解久坐疲劳'
					},
					{
						time: '18:00',
						title: '晚餐时间',
						description: '清淡饮食，避免过饱'
					},
					{
						time: '22:00',
						title: '准备睡眠',
						description: '放松身心，准备入睡'
					}
				],
				healthRemindersCustom: [],
				showModal: false,
				selectedKnowledge: {},
				showReminderModal: false,
				newReminder: {
					time: '',
					title: '',
					description: ''
				},
				showReportModal: false,
				reportContent: '',
				reportContentHtml: '',
				reminderErrors: {
					time: '',
					title: '',
					description: ''
				},
				reminderCheckTimer: null,
				adviceFavorites: [],
				showAdviceDetailModal: false,
				adviceDetail: {},
				showExportFavoritesModal: false,
				exportFavoritesContent: '',
				isMpWeixin: false,
				canNativeShare: false,
				userInfo: null, // 用户信息
				isLoadingCloudData: false, // 云端数据加载状态
			}
		},
		onLoad() {
			// 登录校验
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				uni.redirectTo({
					url: '/pages/login/login'
				})
				return
			}
			this.userInfo = userInfo
			this.loadHealthData()
			this.loadCloudData() // 加载云端数据
			// 判断平台
			// #ifdef MP-WEIXIN
			this.isMpWeixin = true
			// #endif
			// #ifdef H5
			this.canNativeShare = !!(navigator.share)
			// #endif
			// #ifdef APP-PLUS
			this.canNativeShare = true
			// #endif
		},
		onShow() {
			// 登录校验
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				uni.redirectTo({
					url: '/pages/login/login'
				})
				return
			}
			this.userInfo = userInfo
			// 只加载数据库历史建议
			this.loadCloudAdvice()
			this.loadCloudData() // 收藏和提醒
			this.startReminderCheck()

		},
		onHide() {
			this.stopReminderCheck()
		},
		onUnload() {
			this.stopReminderCheck()
		},
		methods: {
			// 加载云端数据
			async loadCloudData() {
				if (!this.userInfo || this.isLoadingCloudData) return

				this.isLoadingCloudData = true
				try {
					// 并行加载收藏和提醒数据
					const [favoritesRes, remindersRes] = await Promise.allSettled([
						favoritesAPI.getFavorites(this.userInfo.userId),
						remindersAPI.getReminders(this.userInfo.userId)
					])

					// 处理收藏数据
					if (favoritesRes.status === 'fulfilled' && favoritesRes.value) {
						this.adviceFavorites = favoritesRes.value.map(item => ({
							...item,
							tags: item.tags ? item.tags.split(',') : []
						}))
						uni.setStorageSync('adviceFavorites', this.adviceFavorites)
						console.log('云端收藏数据加载成功:', this.adviceFavorites)
					}

					// 处理提醒数据
					if (remindersRes.status === 'fulfilled' && remindersRes.value) {
						this.healthRemindersCustom = remindersRes.value.map(item => ({
							...item,
							notified: Boolean(item.notified)
						}))
						uni.setStorageSync('customReminders', this.healthRemindersCustom)
						console.log('云端提醒数据加载成功:', this.healthRemindersCustom)
					}

				} catch (error) {
					console.error('加载云端数据失败:', error)
					// 如果云端加载失败，使用本地缓存数据
					this.loadLocalData()
				} finally {
					this.isLoadingCloudData = false
				}
			},

			// 加载历史建议记录（当没有当前健康数据时）
			async loadHistoricalAdvice() {
				if (!this.userInfo) return

				try {
					console.log('加载用户历史建议记录...')
					const historicalResult = await analysisAPI.getAnalysis(this.userInfo.userId)

					if (historicalResult && historicalResult.aiAdvice) {
						// 解析历史建议数据
						const historicalAiAdvice = JSON.parse(historicalResult.aiAdvice)

						// 使用历史建议结果
						this.personalizedAdvice = historicalAiAdvice
						this.connectionError = ''

						// 显示历史数据提示
						uni.showToast({
							title: '已加载历史建议',
							icon: 'success'
						})

						console.log('使用历史建议结果:', this.personalizedAdvice)
					} else {
						// 没有历史数据，显示提示
						this.personalizedAdvice = []
						this.connectionError = '暂无历史建议记录'

						uni.showToast({
							title: '暂无建议记录',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('加载历史建议记录失败:', error)
					// 加载失败，显示提示
					this.personalizedAdvice = []
					this.connectionError = '加载历史记录失败'

					uni.showToast({
						title: '加载历史记录失败',
						icon: 'none'
					})
				}
			},

			showDescript(advice) {
				uni.showModal({
					title: advice.title,
					content: advice.description,
				});
			},
			loadHealthData() {
				const data = uni.getStorageSync('healthData')
				if (data) {
					this.healthData = data
				}
			},
			showKnowledgeDetail(item) {
				this.selectedKnowledge = item
				this.showModal = true
			},
			closeModal() {
				this.showModal = false
			},
			openReminderModal() {
				this.newReminder = {
					time: '',
					title: '',
					description: ''
				}
				this.showReminderModal = true
			},
			closeReminderModal() {
				this.showReminderModal = false
			},
			async addCustomReminder() {
				// 清空错误
				this.reminderErrors = {
					time: '',
					title: '',
					description: ''
				}
				let valid = true
				// 时间校验
				if (!this.newReminder.time) {
					this.reminderErrors.time = '请选择提醒时间'
					valid = false
				}
				// 内容校验
				const title = this.newReminder.title ? this.newReminder.title.trim() : ''
				if (!title) {
					this.reminderErrors.title = '请输入提醒内容'
					valid = false
				} else if (title.length > 30) {
					this.reminderErrors.title = '内容不能超过30字'
					valid = false
				}
				// 描述校验
				const desc = this.newReminder.description ? this.newReminder.description.trim() : ''
				if (desc.length > 50) {
					this.reminderErrors.description = '描述不能超过50字'
					valid = false
				}
				if (!valid) return

				try {
					// 先保存到云端
					const reminderData = {
						time: this.newReminder.time,
						title: title,
						description: desc,
						notified: false
					}

					const res = await remindersAPI.addReminder(this.userInfo.userId, reminderData)

					if (res.success) {
						// 云端保存成功，重新加载云端数据
						await this.loadCloudData()
						this.showReminderModal = false
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						})
					} else {
						// 云端保存失败，保存到本地
						this.healthRemindersCustom.push(reminderData)
						this.saveCustomReminders()
						this.showReminderModal = false
						uni.showToast({
							title: '添加成功（仅本地）',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('添加提醒失败:', error)
					// 保存到本地作为备选
					const reminderData = {
						time: this.newReminder.time,
						title: title,
						description: desc,
						notified: false
					}
					this.healthRemindersCustom.push(reminderData)
					this.saveCustomReminders()
					this.showReminderModal = false
					uni.showToast({
						title: '添加成功（仅本地）',
						icon: 'none'
					})
				}
			},
			async deleteCustomReminder(index) {
				const reminder = this.healthRemindersCustom[index]

				try {
					// 如果有云端ID，先删除云端数据
					if (reminder.id) {
						const res = await remindersAPI.deleteReminder(this.userInfo.userId, reminder.id)
						if (res.success) {
							// 云端删除成功，重新加载数据
							await this.loadCloudData()
							uni.showToast({
								title: '已删除',
								icon: 'none'
							})
							return
						}
					}

					// 云端删除失败或无ID，删除本地数据
					this.healthRemindersCustom.splice(index, 1)
					this.saveCustomReminders()
					uni.showToast({
						title: '已删除（仅本地）',
						icon: 'none'
					})
				} catch (error) {
					console.error('删除提醒失败:', error)
					// 删除本地数据作为备选
					this.healthRemindersCustom.splice(index, 1)
					this.saveCustomReminders()
					uni.showToast({
						title: '已删除（仅本地）',
						icon: 'none'
					})
				}
			},
			saveCustomReminders() {
				uni.setStorageSync('customReminders', this.healthRemindersCustom)
			},
			loadCustomReminders() {
				this.healthRemindersCustom = uni.getStorageSync('customReminders') || []
			},
			shareHealth() {
				uni.showActionSheet({
					itemList: ['分享我的收藏', '分享健康报告'],
					success: (res) => {
						if (res.tapIndex === 0) {
							this.openExportFavoritesModal()
						} else if (res.tapIndex === 1) {
							this.openReportModal()
						}
					}
				})
			},
			async openReportModal() {
				console.log('openReportModal');
				this.reportContent = '报告加载中...'
				this.reportContentHtml = this.reportContent.replace(/\n/g, '<br/>')
				this.showReportModal = true

				try {
					const res = await analysisAPI.getAnalysis(this.userInfo.userId)
					console.log(res);

					let healthData = res && res.healthData
					if (typeof healthData === 'string') {
						try {
							healthData = JSON.parse(healthData)
						} catch (e) {
							healthData = {}
						}
					}
					let aiAdvice = res && res.aiAdvice
					if (typeof aiAdvice === 'string') {
						try {
							aiAdvice = JSON.parse(aiAdvice)
						} catch (e) {
							aiAdvice = []
						}
					}
					this.healthData = healthData
					this.personalizedAdvice = aiAdvice

					this.reportContent = this.generateReport()
					this.reportContentHtml = this.reportContent.replace(/\n/g, '<br/>')
				} catch (e) {
					this.reportContent = '云端数据获取失败'
					this.reportContentHtml = this.reportContent
				}
			},
			closeReportModal() {
				this.showReportModal = false
			},
			generateReport() {
				if (!this.healthData) return '暂无健康数据'
				let report =
					`【健康数据报告】\n\n基本信息：\n年龄：${this.healthData.age}\n性别：${this.healthData.gender}\n身高：${this.healthData.height}cm\n体重：${this.healthData.weight}kg\nBMI：${this.healthData.bmi}\n血压：${this.healthData.bloodPressure}（${this.healthData.bloodPressureStatus}）\n\n生活习惯：\n运动：${this.healthData.exercise}\n睡眠：${this.healthData.sleep}\n吸烟：${this.healthData.smoke}\n\nAI个性化建议：\n`
				this.personalizedAdvice.forEach((item, idx) => {
					// 兼容不同字段名
					const title = item.title || item.建议类型 || item.type || `建议${idx+1}`
					const content = item.content || item.建议内容 || item.desc || item.description || ''
					report += `${idx + 1}. ${title}：${content}\n`
				})
				return report
			},
			copyReport() {
				uni.setClipboardData({
					data: this.reportContent,
					success: () => {
						uni.showToast({
							title: '已复制到剪贴板',
							icon: 'success'
						})
					}
				})
			},
			contactDoctor() {
				uni.showModal({
					title: '医生咨询',
					content: '如需咨询医生，请拨打客服电话：400-123-4567\n或关注我们的公众号获取更多服务。',
					showCancel: false
				})
			},
			validateReminderTitle() {
				const title = this.newReminder.title ? this.newReminder.title.trim() : ''
				if (!title) {
					this.reminderErrors.title = '请输入提醒内容'
				} else if (title.length > 30) {
					this.reminderErrors.title = '内容不能超过30字'
				} else {
					this.reminderErrors.title = ''
				}
			},
			validateReminderDesc() {
				const desc = this.newReminder.description ? this.newReminder.description.trim() : ''
				if (desc.length > 50) {
					this.reminderErrors.description = '描述不能超过50字'
				} else {
					this.reminderErrors.description = ''
				}
			},
			onReminderDateTimeChange(e) {
				this.newReminder.time = e.detail.value
				this.validateReminderTime()
			},
			validateReminderTime() {
				if (!this.newReminder.time) {
					this.reminderErrors.time = '请选择提醒时间'
					return
				}
				const now = new Date().getTime()
				const pick = new Date(this.newReminder.time.replace(/-/g, '/')).getTime()
				if (isNaN(pick)) {
					this.reminderErrors.time = '时间格式不正确'
					return
				}
				if (pick < now) {
					this.reminderErrors.time = '提醒时间不能早于当前时间'
				} else {
					this.reminderErrors.time = ''
				}
			},
			startReminderCheck() {
				if (this.reminderCheckTimer) clearInterval(this.reminderCheckTimer)
				this.reminderCheckTimer = setInterval(this.checkReminders, 30000) // 30秒检查一次
				this.checkReminders() // 进入页面立即检查一次
			},
			stopReminderCheck() {
				if (this.reminderCheckTimer) {
					clearInterval(this.reminderCheckTimer)
					this.reminderCheckTimer = null
				}
			},
			checkReminders() {
				const now = new Date().getTime()
				let updated = false
				this.healthRemindersCustom.forEach((reminder, idx) => {
					if (!reminder.notified && reminder.time) {
						let remindTime = reminder.time
						if (remindTime.length === 5) { // 兼容旧time格式
							const today = new Date()
							remindTime =
								`${today.getFullYear()}/${today.getMonth()+1}/${today.getDate()} ${remindTime}`
						} else {
							remindTime = remindTime.replace(/-/g, '/').replace('T', ' ')
						}
						const remindTimestamp = new Date(remindTime).getTime()
						// 只要当前时间大于等于提醒时间，且未提醒过，就提醒一次
						if (!isNaN(remindTimestamp) && remindTimestamp <= now) {
							reminder.notified = true // 先标记，防止多次弹窗
							updated = true
							this.saveCustomReminders() // 立即保存，防止多次提醒
							this.$nextTick(() => {
								uni.showModal({
									title: '健康提醒',
									content: `${reminder.title}${reminder.description ? '\n' + reminder.description : ''}`,
									showCancel: false
								})
							})
							this.deleteCustomReminder(idx)
						}
					}
				})
				// 不再需要if (updated) this.saveCustomReminders()，已在弹窗前保存
			},
			isFavorite(advice) {
				return this.adviceFavorites.some(fav => fav.title === advice.title && fav.content === advice.content)
			},
			async toggleFavorite(advice) {
				console.log(advice);
				const isFav = this.isFavorite(advice)

				try {
					if (isFav) {
						// 取消收藏
						const fav = this.adviceFavorites.find(f => f.title === advice.title && f.content === advice
							.content)
						if (fav && fav.id) {
							const res = await favoritesAPI.deleteFavorite(this.userInfo.userId, fav.id)
							if (res.success) {
								await this.loadCloudData()
								uni.showToast({
									title: '已取消收藏',
									icon: 'none'
								})
								return
							}
						}
						// 云端删除失败或无ID，删除本地
						const idx = this.adviceFavorites.findIndex(fav => fav.title === advice.title && fav.content ===
							advice.content)
						if (idx > -1) {
							this.adviceFavorites.splice(idx, 1)
							this.saveAdviceFavorites()
						}
						uni.showToast({
							title: '已取消收藏',
							icon: 'none'
						})
					} else {

						// 添加收藏
						console.log('收藏的advice对象:', advice);
						console.log('advice.title:', advice.title);
						console.log('advice.description:', advice.description);
						console.log('advice.content:', advice.content);

						const res = await favoritesAPI.addFavorite(this.userInfo.userId, {
							title: advice.title || '',
							content: advice.content || advice.description || '',
							tags: advice.tags || []
						})
						console.log(res);


						if (res.success) {
							await this.loadCloudData()
							uni.showToast({
								title: '已收藏',
								icon: 'success'
							})
						} else {
							// 云端添加失败，保存到本地
							this.adviceFavorites.push(advice)
							this.saveAdviceFavorites()
							uni.showToast({
								title: '已收藏（仅本地）',
								icon: 'none'
							})
						}
					}
				} catch (error) {
					console.error('收藏操作失败:', error)
					// 操作失败，使用本地存储作为备选
					if (isFav) {
						const idx = this.adviceFavorites.findIndex(fav => fav.title === advice.title && fav.content ===
							advice.content)
						if (idx > -1) {
							this.adviceFavorites.splice(idx, 1)
							this.saveAdviceFavorites()
						}
						uni.showToast({
							title: '已取消收藏（仅本地）',
							icon: 'none'
						})
					} else {
						this.adviceFavorites.push(advice)
						this.saveAdviceFavorites()
						uni.showToast({
							title: '已收藏（仅本地）',
							icon: 'none'
						})
					}
				}
			},
			saveAdviceFavorites() {
				uni.setStorageSync('adviceFavorites', this.adviceFavorites)
			},
			loadAdviceFavorites() {
				this.adviceFavorites = uni.getStorageSync('adviceFavorites') || []
			},
			openAdviceDetail(advice) {
				this.adviceDetail = advice
				this.showAdviceDetailModal = true
			},
			closeAdviceDetailModal() {
				this.showAdviceDetailModal = false
			},
			openExportFavoritesModal() {
				this.exportFavoritesContent = this.generateExportFavorites()
				this.showExportFavoritesModal = true
			},
			closeExportFavoritesModal() {
				this.showExportFavoritesModal = false
			},
			generateExportFavorites() {
				if (!this.adviceFavorites.length) return '暂无收藏建议'
				let text = '【我的健康建议收藏】\n\n'
				this.adviceFavorites.forEach((item, idx) => {
					const title = item.title || ''
					const content = item.content || item.description || ''
					const tags = item.tags && item.tags.length ? ' [' + item.tags.join(', ') + ']' : ''
					text += `${idx+1}. ${title}${tags}\n${content}\n\n`
				})
				return text
			},
			copyExportFavorites() {
				uni.setClipboardData({
					data: this.exportFavoritesContent,
					success: () => {
						uni.showToast({
							title: '已复制到剪贴板',
							icon: 'success'
						})
					}
				})
			},
			shareFavorites() {
				// #ifdef H5
				if (navigator.share) {
					navigator.share({
						title: '我的健康建议收藏',
						text: this.exportFavoritesContent,
						url: window.location.href
					}).then(() => {
						uni.showToast({
							title: '分享成功',
							icon: 'success'
						})
					}).catch(() => {
						uni.showToast({
							title: '分享已取消',
							icon: 'none'
						})
					})
				} else {
					uni.showToast({
						title: '当前浏览器不支持原生分享',
						icon: 'none'
					})
				}
				// #endif
				// #ifdef APP-PLUS
				uni.share({
					provider: 'weixin', // 可选：weixin、qq、sinaweibo等
					type: 0, // 0为文本
					summary: this.exportFavoritesContent,
					success: () => {
						uni.showToast({
							title: '分享成功',
							icon: 'success'
						})
					},
					fail: () => {
						uni.showToast({
							title: '分享失败',
							icon: 'none'
						})
					}
				})
				// #endif
				// #ifdef MP-WEIXIN
				uni.showToast({
					title: '请用下方按钮或右上角菜单分享',
					icon: 'none'
				})
				// #endif
			},
			onShareAppMessage() {
				return {
					title: '我的健康建议收藏',
					desc: '快来看看我的健康建议收藏吧！',
					path: '/pages/advice/advice'
				}
			},
			// 加载本地缓存数据（作为备选）
			loadLocalData() {
				this.adviceFavorites = uni.getStorageSync('adviceFavorites') || []
				this.healthRemindersCustom = uni.getStorageSync('customReminders') || []
			},
			// 只加载数据库历史建议
			async loadCloudAdvice() {
				if (!this.userInfo) return
				try {
					const cloudResult = await analysisAPI.getAnalysis(this.userInfo.userId)
					if (cloudResult && cloudResult.aiAdvice) {
						const cloudAiAdvice = JSON.parse(cloudResult.aiAdvice)

						// 兼容处理字段名
						this.personalizedAdvice = Array.isArray(cloudAiAdvice) ? cloudAiAdvice.map(item => {
							console.log('处理建议项:', item);
							return {
								icon: item.icon || '💡',
								title: item.title || item.建议类型 || item.type || '健康建议',
								content: item.content || item.description || item.建议内容 || item.desc || item
									.内容 || '',
								description: item.content || item.description || item.建议内容 || item.desc || item
									.内容 || '', // 保持兼容性
								tags: item.tags || []
							}
						}) : []

						this.connectionError = ''
						uni.showToast({
							title: '已加载历史建议',
							icon: 'success'
						})
					} else {
						this.personalizedAdvice = []
						this.connectionError = '暂无建议记录'
						uni.showToast({
							title: '暂无建议记录',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('加载云端建议失败:', error)
					this.personalizedAdvice = []
					this.connectionError = '加载云端失败'
					uni.showToast({
						title: '加载云端失败',
						icon: 'none'
					})
				}
			},
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.header {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}

	.subtitle {
		font-size: 26rpx;
		color: #666;
	}

	.personalized-section {
		margin-bottom: 30rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.header-actions {
		display: flex;
		gap: 20rpx;
	}

	.refresh-btn {
		background: linear-gradient(135deg, #4CAF50, #45a049);
		color: white;
		border: none;
		border-radius: 15rpx;
		padding: 10rpx 20rpx;
		font-size: 28rpx;
		font-weight: bold;
	}

	.connection-status {
		background: #fff3cd;
		border: 1rpx solid #ffeaa7;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-top: 20rpx;
		text-align: center;
	}

	.status-text {
		font-size: 28rpx;
		color: #856404;
		display: block;
		margin-bottom: 10rpx;
	}

	.status-hint {
		font-size: 24rpx;
		color: #856404;
	}

	.loading-advice {
		background: white;
		border-radius: 15rpx;
		padding: 60rpx 40rpx;
		text-align: center;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.loading-icon {
		font-size: 60rpx;
		margin-bottom: 20rpx;
	}

	.loading-text {
		font-size: 28rpx;
		color: #666;
	}

	.advice-cards {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.advice-card {
		background: white;
		border-radius: 15rpx;
		padding: 25rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.card-header {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.card-icon {
		font-size: 40rpx;
		margin-right: 15rpx;
	}

	.card-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}

	.card-content {
		font-size: 26rpx;
		color: #666;
		line-height: 1.5;
		margin-bottom: 15rpx;
		display: block;
	}

	.card-tags {
		display: flex;
		flex-wrap: wrap;
		gap: 10rpx;
	}

	.tag {
		background: #e8f5e8;
		color: #4CAF50;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		font-size: 22rpx;
	}

	.knowledge-section {
		margin-bottom: 30rpx;
	}

	.knowledge-list {
		background: white;
		border-radius: 15rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.knowledge-item {
		display: flex;
		align-items: center;
		padding: 25rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.knowledge-item:last-child {
		border-bottom: none;
	}

	.item-icon {
		font-size: 40rpx;
		margin-right: 20rpx;
	}

	.item-content {
		flex: 1;
	}

	.item-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 5rpx;
	}

	.item-desc {
		font-size: 24rpx;
		color: #666;
	}

	.item-arrow {
		font-size: 28rpx;
		color: #ccc;
	}

	.reminder-section {
		margin-bottom: 30rpx;
	}

	.reminder-list {
		background: white;
		border-radius: 15rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.reminder-item {
		display: flex;
		align-items: center;
		padding: 25rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.reminder-item:last-child {
		border-bottom: none;
	}

	.reminder-time {
		background: #4CAF50;
		color: white;
		padding: 10rpx 15rpx;
		border-radius: 10rpx;
		font-size: 24rpx;
		font-weight: bold;
		margin-right: 20rpx;
		min-width: 80rpx;
		text-align: center;
	}

	.reminder-content {
		flex: 1;
	}

	.reminder-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 5rpx;
	}

	.reminder-desc {
		font-size: 24rpx;
		color: #666;
	}

	.reminder-delete {
		color: #ff4757;
		font-size: 24rpx;
		margin-left: 20rpx;
		cursor: pointer;
	}

	.quick-actions {
		margin-bottom: 30rpx;
	}

	.action-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 20rpx;
	}

	.action-item {
		background: white;
		border-radius: 15rpx;
		padding: 30rpx;
		text-align: center;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.action-icon {
		font-size: 50rpx;
		margin-bottom: 15rpx;
	}

	.action-text {
		font-size: 26rpx;
		color: #333;
	}

	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 999;
	}

	.modal-content {
		background: white;
		border-radius: 15rpx;
		width: 90%;
		max-height: 80%;
		overflow: hidden;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.modal-close {
		font-size: 40rpx;
		color: #ccc;
		width: 40rpx;
		height: 40rpx;
		text-align: center;
		line-height: 40rpx;
	}

	.modal-body {
		padding: 30rpx;
		max-height: 60vh;
	}

	.modal-text {
		font-size: 28rpx;
		color: #333;
		line-height: 1.6;
	}

	.form-item {
		margin-bottom: 20rpx;
	}

	.label {
		display: block;
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}

	.input {
		width: 100%;
		padding: 10rpx;
		border: 1rpx solid #ccc;
		border-radius: 10rpx;
	}

	.save-btn {
		background: linear-gradient(135deg, #4CAF50, #45a049);
		color: white;
		border: none;
		border-radius: 10rpx;
		padding: 10rpx 20rpx;
		font-size: 28rpx;
		font-weight: bold;
	}

	.error-text {
		color: #ff4757;
		font-size: 24rpx;
		margin-top: 8rpx;
		display: block;
	}

	.favorite-btn {
		margin-left: auto;
		cursor: pointer;
	}

	.star {
		font-size: 32rpx;
		color: #ccc;
		transition: color 0.2s;
	}

	.star.active {
		color: #FFD700;
	}

	.favorite-section {
		margin-bottom: 30rpx;
	}

	.modal-body .save-btn {
		margin-top: 10rpx;
		background: linear-gradient(135deg, #FFD700, #FFB300);
		color: #333;
	}

	.history-tip {
		color: #666;
		background: #f0f8ff;
		border-radius: 10rpx;
		padding: 20rpx;
		margin: 20rpx 0;
		font-size: 28rpx;
		text-align: center;
	}
</style>